package com.mutable.app.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.mutable.app.mapper1", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class MysqlSqlConfig1 {

    private static final Logger logger = LoggerFactory.getLogger(MysqlSqlConfig1.class);

    @Bean(name = "test1Datasource")
    @ConfigurationProperties(prefix = "mysql.datasource.test1")
    public DataSource test1Datasource() {
        return DataSourceBuilder.create().build();
    }

    @Autowired
    @Bean(name = "test1SqlSessionFactory")
    public SqlSessionFactory test1SessionFacotry(@Qualifier("test1Datasource")DataSource dataSource) throws Exception {

        SqlSessionFactoryBean sessionBean = new SqlSessionFactoryBean();
        sessionBean.setDataSource(dataSource);
        logger.info("init ---- datasource1  completed!");
        return sessionBean.getObject();
    }

    @Autowired
    @Bean(name = "test1TransactionManager")
    public DataSourceTransactionManager test1TransactionManager(@Qualifier("test1Datasource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

}
